/*
 * @lc app=leetcode.cn id=188 lang=cpp
 *
 * [188] 买卖股票的最佳时机 IV
 */

// @lc code=start
class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        k = min(k, n / 2);
        vector<vector<int>> dp(k + 1, vector<int>(2));
        dp[0][0] = 0;
        dp[0][1] = INT_MIN / 2;
        for (int j = 0; j < n; ++j) {
            for (int i = k; i > 0; --i) {
                if (j == 0) {
                    dp[i][0] = 0;
                    dp[i][1] = -prices[j];
                }
                dp[i][0] = max(dp[i][0], dp[i][1] + prices[j]);
                dp[i][1] = max(dp[i][1], dp[i - 1][0] - prices[j]);
            }
        }
        return dp[k][0];
    }
};
// @lc code=end

